package com.chain.BrotherExchange.ui.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;

import com.chain.BrotherExchange.C;
import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.data.DataRepository;
import com.chain.BrotherExchange.data.Resource;
import com.chain.BrotherExchange.data.model.LegalTenderDealList;
import com.chain.BrotherExchange.data.model.UserPayment;
import com.chain.BrotherExchange.event.EditTransactionOrderEvent;
import com.chain.BrotherExchange.ui.activity.EditTransactionOrderActivity;
import com.chain.BrotherExchange.ui.adapter.LegalTenderMyTransactionListAdapter;
import com.chain.BrotherExchange.ui.core.AbsNetworkStateFragment;
import com.chain.BrotherExchange.utils.Androids;
import com.chain.BrotherExchange.viewmodel.LegalTenderDealViewModel;
import com.chain.BrotherExchange.viewmodel.PaymentViewModel;
import com.chain.BrotherExchange.viewmodel.core.ViewModelProviders;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import org.greenrobot.eventbus.Subscribe;

import butterknife.Bind;

/**
 * 去的交易单
 */
public class MyTransactionOrderFragment extends AbsNetworkStateFragment implements OnRefreshLoadmoreListener {

    private PaymentViewModel mPaymentViewModel;
    private UserPayment.DataBean.SetpaysBean mPayments;

    public static Fragment newInstance(int pageType) {
        MyTransactionOrderFragment fragment = new MyTransactionOrderFragment();
        Bundle args = new Bundle();
        args.putInt(C.EXTRA_PAGE_TYPE, pageType);
        fragment.setArguments(args);
        return fragment;
    }

    @Bind(R.id.recycler_view) RecyclerView mRecyclerView;
    @Bind(R.id.smart_refresh_layout) SmartRefreshLayout mSmartRefreshLayout;

    private int mUid;
    private int mPageType;
    private LegalTenderDealViewModel mViewModel;
    private LegalTenderMyTransactionListAdapter mAdapter;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.simple_load_refresh_recycler_view;
    }

    @Override
    protected void initActions() {
        mUid = Androids.LocalConfig.getUid();
        mPageType = getArguments().getInt(C.EXTRA_PAGE_TYPE);

        // 初始化列表
        mAdapter = new LegalTenderMyTransactionListAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(this);
        mAdapter.setOrderActionListener(this::orderAction);
        mAdapter.setEditOrderListener(this::editTransactionOrder);
        mAdapter.setDeleteOrderListener(this::deleteTransactionOrder);

        // 数据
        mPaymentViewModel = ViewModelProviders.of(this).get(PaymentViewModel.class);
        mViewModel = ViewModelProviders.of(this).get(LegalTenderDealViewModel.class);

        initLegalTenderDealList();
    }

    private void initLegalTenderDealList() {
        mViewModel.newLegalTenderUserDealList(mPageType, mUid).observe(this, resource -> {
                    if (mSmartRefreshLayout.isRefreshing()) {
                        mSmartRefreshLayout.finishRefresh();
                    }

                    Resource.load(getContext(), resource, this, result ->
                            mAdapter.setLegalTenderDealList(result)
                    );
                }
        );
    }

    // 删除订单
    private void deleteTransactionOrder(AdapterView<?> adapterView, View view, int position, long l) {
        int id = mAdapter.getItem(position).getId();
        String token = Androids.LocalConfig.getToken();
        int uid = Androids.LocalConfig.getUid();
        view.setFocusable(false);
        DataRepository.get().editMyPublishTransactionOrderStatus(uid, token, id, 4, result -> {
            Androids.makeText(result.getMsg());
            if (result.isSucceed()) {
                view.setFocusable(true);
                mAdapter.removeItem(position);
            }
        });
    }

    // 编辑订单
    private void editTransactionOrder(AdapterView<?> adapterView, View view, int position, long l) {
        LegalTenderDealList.DataBean.ListBean item = mAdapter.getItem(position);
        EditTransactionOrderActivity.launch(getContext(), item);
    }

    // 上下架订单
    private void orderAction(AdapterView<?> adapterView, View view, int position, long l) {
        int states = mAdapter.getItem(position).getStates();
        int id = mAdapter.getItem(position).getId();
        int stateId;
        if (states == 0) { // 当前状态为下架状态
            stateId = 2;
        } else {
            stateId = 1;
        }

        mViewModel.editOrderState(stateId, id).observe(this, resource -> {
            if (resource.state == Resource.Status.LOADING) {
                view.setFocusable(false);
            } else {
                Androids.makeText(resource.message);
                if (resource.state == Resource.Status.SUCCESS) {
                    if (states == 0) {
                        mAdapter.getItem(position).setStates(1);
                    } else {
                        mAdapter.getItem(position).setStates(0);
                    }

                    mAdapter.notifyItemChanged(position);
                }
            }
        });
    }

    @Subscribe
    public void editTransactionOrderEvent(EditTransactionOrderEvent event){
        initLegalTenderDealList();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        initLegalTenderDealList();
    }

    @Override
    public void onAnewRequest() {
        initLegalTenderDealList();
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mViewModel.moreLegalTenderUserDealList(mPageType, mUid).observe(this, resource -> {
            switch (resource.state) {
                case EMPTY:
                    Androids.makeText(R.string.no_more);
                    break;
                case NOT_NETWORK:
                    Androids.makeText(R.string.network_error);
                    break;
                case ERROR:
                    Androids.makeText(resource.message);
                    break;
                case SUCCESS:
                    mAdapter.addLegalTenderDealList(resource.source);
                    break;
            }

            mSmartRefreshLayout.finishLoadmore(0);
        });
    }
}
